package com.cositas.dulces.lp.promo2012;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cositas.dulces.lp.promo2012.dbentities.Coupon;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class AddSharedCouponAction implements Action {
	
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		BackendAction.checkUser();
		String code = req.getParameter(Coupon.field_code);
		String remain = req.getParameter(Coupon.field_remainder);
		String points = req.getParameter(Coupon.field_points);
		Key k = KeyFactory.createKey(Coupon.entity_name, code);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		try {
			datastore.get(k);
			resp.getWriter().print("NOP");
		} catch (EntityNotFoundException e) {
			Entity coupon = new Entity(k);
			coupon.setProperty(Coupon.field_points, points);
			coupon.setProperty(Coupon.field_shared, Boolean.TRUE);
			coupon.setProperty(Coupon.field_remainder, remain);
			datastore.put(coupon);
			resp.getWriter().print("OK");
		}
	}
}
